package cc.web.vaaking.servlet.system;

import cc.web.vaaking.common.AjaxResult;
import cc.web.vaaking.common.AjaxTool;
import cc.web.vaaking.common.LoginContext;
import cc.web.vaaking.common.LoginUser;
import cc.web.vaaking.entity.SysUser;
import cc.web.vaaking.services.SysUserService;
import cc.web.vaaking.servlet.BaseHttpServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login/*")
public class LoginServlet extends BaseHttpServlet {

    SysUserService sysUserService = new SysUserService();

    @Override
    public void init() throws ServletException {
        routerMap.put("index", this::index);
        routerMap.put("login", this::login);
        routerMap.put("logout", this::logout);
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            LoginContext.removeCurrentUser(request);
            request.getSession().removeAttribute("username");
            AjaxTool.returnAjax(response,AjaxResult.success("success"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void index(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getRequestDispatcher("../views/system/login.jsp").forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) {
        SysUser sysUser = AjaxTool.getJSON(request).toJavaObject(SysUser.class);
        SysUser real = sysUserService.selectByUsername(sysUser.getUsername());
        if(real==null){
            AjaxTool.returnAjax(response,AjaxResult.error("用户不存在"));
        }else if(!real.getPassword().equals(sysUser.getPassword())){
            AjaxTool.returnAjax(response,AjaxResult.error("密码错误"));
        } else{
            LoginUser loginUser = new LoginUser(real);
            LoginContext.setCurrentUser(request,loginUser);
            request.getSession().setAttribute("user",loginUser);
            AjaxTool.returnAjax(response,AjaxResult.success(sysUser));
        }

    }

}
